package com.demo.weixin.pdf;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

public class PdfFormFiller {
    // 表单字段映射（根据实际模板修改）
    private static final String FIELD_NAME = "name";
    private static final String FIELD_STUDENT_ID = "uname";
    private static final String FIELD_ISSUE_DATE = "date";
    private static final String FIELD_CERT_NO = "number";

    public static void main(String[] args) {
        String tmp = "C:\\Users\\Administrator\\Pictures\\资料\\实验室安全教育考试合格证(横版2020).pdf";
        String cert = "C:\\Users\\Administrator\\Pictures\\资料\\filled_cert.pdf";
        try {
            // 1. 加载模板
            PdfDocument pdfDoc = new PdfDocument(
                    new PdfReader(tmp),
                    new PdfWriter(cert)
            );

            // 2. 获取表单对象
            PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);

            // 3. 加载中文字体
            PdfFont font = PdfFontFactory.createFont(
                    "C:\\Users\\Administrator\\Pictures\\资料\\SourceHanSerifCN-Regular-1.otf",
                    PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED
            );

            // 4. 填充表单数据
            fillField(form, FIELD_NAME, "张三", font, 34);
            fillField(form, FIELD_STUDENT_ID, "20231001", font, 34);
            fillField(form, FIELD_ISSUE_DATE, "2024年3月20日", font, 32);
            fillField(form, FIELD_CERT_NO, "CER-2024-001", font, 32);

            // 5. 锁定表单（可选）
            form.flattenFields();

            pdfDoc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void fillField(PdfAcroForm form, String fieldName,
                                  String value, PdfFont font, float fontSize) {
        PdfFormField field = form.getField(fieldName);
        if (field != null) {
            field.setFont(font).setFontSize(fontSize);
            field.setValue(value);
        } else {
            System.err.println("字段不存在: " + fieldName);
        }
    }
}
